<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>异步并发请求</title>
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
    }
  </style>
</head>

<body>
  <div></div>
</body>
<script>
  "use strict"; {
    /** 
     * @description 异步并发请求
     * @param urls 请求的 url 数组
     * @param maxNum 最大并发数
    */
    function concurRequest(urls = [], maxNum = 3) {
      return new Promise((resolve) => {
        let len = urls.length;
        if (len === 0) {
          resolve([]);
          return;
        };

        // 如果并发数大于数组长度，则使用数组的长度
        maxNum = Math.min(len, maxNum);

        // 请求得到的结果
        let result = [];
        let index = 0;

        // 请求处理---
        let fn = async (i = 0) => {
          let url = urls[i];
          try {
            let res = await fetch(url);
            result[i] = res;
          } catch (err) {
            result[i] = err;
          } finally {
            if (result.length === len) { // 说明此时，已经全部执行了
              resolve(result);
              return;
            };

            index++
            // 每次请求结果后
            fn(index);
          };
        };
        // 请求处理===

        do {
          index++;
          fn(index)
        } while (index <= maxNum);

      });
    };

    let url = [
      `https://www.baidu.com/`,
      `https://www.baidu.com/`,
      `https://www.baidu.com/`,
      `https://www.baidu.com/`,
      `https://www.baidu.com/`,
    ];
    concurRequest(url);
  };
</script>

</html>